#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;
const std::string BlankLine = "\r\n";

class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return this->HandlerHttpRequest(sockfd, client); });
        _tsvr->Loop();
    }

    // 就是我们处理的http的入口
    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << "addr info: " << client.Addr();
        std::string http_request; // 获取别人发送的http请求
        sockfd->Recv(&http_request);
        std::cout << http_request << std::endl; // 在控制台打印出来看看字节流的请求

        // std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title>hello world</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> hellowrold</ p>\
        //                    </body> </html>";
        // std::string httpresponse = status_line + body;
        // sockfd->Send(httpresponse);
        // LOG(LogLevel::DEBUG) << " sucess ";

        HttpRequest req;
        req.Deserialize(http_request); //请求反序列化
        HttpResponse resp;
        resp.Build(req);
        std::string resp_str ;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        
        return true;
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
};
